<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    width="650px"
    destroyOnClose
    showFooter
  >
    <template #title>
      权限配置
      <a-dropdown>
        <Icon icon="ant-design:more-outlined" class="more-icon" />
        <template #overlay>
          <a-menu @click="treeMenuClick">
            <a-menu-item key="checkAll">选择全部</a-menu-item>
            <a-menu-item key="cancelCheck">取消选择</a-menu-item>
            <div class="line"></div>
            <a-menu-item key="openAll">展开全部</a-menu-item>
            <a-menu-item key="closeAll">折叠全部</a-menu-item>
            <div class="line"></div>
            <a-menu-item key="relation">层级关联</a-menu-item>
            <a-menu-item key="standAlone">层级独立</a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>
    </template>
    <a-tabs v-model:activeKey="activeKey">
      <a-tab-pane key="1" tab="页面权限">
        <a-tree
          ref="treeRef"
          checkable
          :treeData="treeData"
          :fieldNames="fieldNames"
          :checkStrictly="true"
          v-model:checkedKeys="checkedKeys"
          title="所拥有的的权限"
          @check="onCheck"
        >
        </a-tree
      ></a-tab-pane>
      <a-tab-pane key="2" tab="机构权限" force-render>
        <a-checkbox-group v-model:value="organizationTreecheckedKeys" style="width: 100%">
          <a-row>
            <a-col :span="24">
              <a-checkbox v-for="item in organizationData" :key="item.id" :value="item.id">{{
                item.name
              }}</a-checkbox>
            </a-col>
          </a-row>
        </a-checkbox-group>
      </a-tab-pane>
    </a-tabs>

    <!--右下角按钮-->
    <template #footer>
      <PopConfirmButton
        title="确定放弃编辑？"
        @confirm="closeDrawer"
        okText="确定"
        cancelText="取消"
        >取消</PopConfirmButton
      >
      <a-button @click="handleSubmit(true)" type="primary" :loading="loading"
        >保存并关闭</a-button
      >
    </template>
    <RoleDataRuleDrawer @register="registerDrawer1" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, computed, unref, onMounted } from "vue";
import { BasicDrawer, useDrawer, useDrawerInner } from "/src/components/Drawer";
import { BasicTree, TreeItem } from "/src/components/Tree";
import { PopConfirmButton } from "/@/components/Button";
import RoleDataRuleDrawer from "./RoleDataRuleDrawer.vue";
import { useSuccess } from "/@/hooks/rw/handleSuccess";
const { rhandleSuccess } = useSuccess();
import { useMessage } from "/@/hooks/web/useMessage";
const { createMessage } = useMessage();
const activeKey = ref<string>("1");
import {
  queryTreeListForRole,
  queryRolePermission,
  saveRolePermission,
  saveOrganizationPermission,
  queryOrganizationPermission,
  getOrganizationTrees,
} from "../role.api";
const emit = defineEmits(["register"]);
//树的信息
const treeData = ref<TreeItem[]>([]);
const organizationData = ref<TreeItem[]>([]);
//树的全部节点信息
const allTreeKeys = ref([]);
//树的选择节点信息
const checkedKeys = ref([]);
const organizationTreecheckedKeys = ref([]);
const defaultCheckedKeys = ref([]);
//树的选中的节点信息
const selectedKeys = ref([]);
const roleId = ref("");
//树的实例
const treeRef = ref(null);
const loading = ref(false);

//展开折叠的key
const expandedKeys = ref<any>([]);
//父子节点选中状态是否关联
const checkStrictly = ref<boolean>(true);
const fieldNames = {
  children: "children",
  title: "name",
  key: "id",
};
const [registerDrawer1, { openDrawer: openDataRuleDrawer }] = useDrawer();
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  await reset();
  setDrawerProps({ confirmLoading: false, loading: true });
  roleId.value = data.roleId;
  //初始化数据
  const roleResult = await queryTreeListForRole();
  treeData.value = roleResult.data.treeList;
  allTreeKeys.value = roleResult.data.ids;
  expandedKeys.value = roleResult.data.ids;
  //初始化角色菜单数据
  const permResult = await queryRolePermission(roleId.value);
  checkedKeys.value = permResult.data;
  defaultCheckedKeys.value = permResult.data;
  setDrawerProps({ loading: false });
  // 初始化病区权限数据
  const organizationTreeResult = await getOrganizationTrees();
  organizationData.value = organizationTreeResult.data;
  //初始化病区权限数据
  const organizationResult = await queryOrganizationPermission(roleId.value);
  organizationTreecheckedKeys.value = organizationResult.data;
});
/**
 * 点击选中
 */
function onCheck(o) {
  checkedKeys.value = o.checked ? o.checked : o;
}
/**
 * 数据重置
 */
function reset() {
  treeData.value = [];
  allTreeKeys.value = [];
  checkedKeys.value = [];
  organizationTreecheckedKeys.value = [];
  defaultCheckedKeys.value = [];
  selectedKeys.value = [];
  roleId.value = "";
}
/**
 * 获取tree实例
 */
function getTree() {
  const tree = unref(treeRef);
  console.log(tree, "tree");
  if (!tree) {
    throw new Error("tree is null!");
  }
  return tree;
}
/**
 * 提交
 */
async function handleSubmit(exit) {
  let params = {
    roleId: unref(roleId),
    ids: unref(getTree().checkedKeys),
    // lastpermissionIds: unref(defaultCheckedKeys).join(","),
  };
  let organizationparams = {
    roleId: unref(roleId),
    organizationIds: unref(organizationTreecheckedKeys),
    // lastpermissionIds: unref(defaultCheckedKeys).join(","),
  };
  //update-begin-author:taoyan date:2023-2-11 for: issues/352 VUE角色授权重复保存
  if (loading.value === false) {
    await doSave(params, organizationparams);
  } else {
    console.log("请等待上次执行完毕!");
  }
  if (exit) {
    // 如果关闭
    closeDrawer();
  } else {
    // 没有关闭需要重新获取选中数据
    const permResult = await queryRolePermission({ roleId: unref(roleId) });
    defaultCheckedKeys.value = permResult;
  }
}

// VUE角色授权重复保存 #352
async function doSave(params, organizationparams) {
  try {
    loading.value = true;
    let res;
    if (params.ids) {
      res = await saveRolePermission(params);
    }
    if (organizationparams.organizationIds) {
      res = await saveOrganizationPermission(organizationparams);
    }

    rhandleSuccess(res, () => {});
    setTimeout(() => {
      loading.value = false;
      activeKey.value = "1";
    }, 500);
  } catch {
    createMessage.error("提交错误");
    setTimeout(() => {
      loading.value = false;
      activeKey.value = "1";
    }, 500);
  }
}

/**
 * 树菜单选择
 * @param key
 */
function treeMenuClick({ key }) {
  if (key === "checkAll") {
    checkedKeys.value = allTreeKeys.value;
  } else if (key === "cancelCheck") {
    checkedKeys.value = [];
  } else if (key === "openAll") {
    expandedKeys.value = allTreeKeys.value;
  } else if (key === "closeAll") {
    expandedKeys.value = [];
  } else if (key === "relation") {
    checkStrictly.value = false;
  } else {
    checkStrictly.value = true;
  }
}
</script>

<style lang="less" scoped>
/** 固定操作按钮 */
.jeecg-basic-tree {
  position: absolute;
  width: 618px;
}
//update-begin---author:wangshuai ---date:20230202  for：抽屉弹窗标题图标下拉样式------------
.line {
  height: 1px;
  width: 100%;
  border-bottom: 1px solid #f0f0f0;
}
.more-icon {
  font-size: 20px !important;
  color: black;
  display: inline-flex;
  float: right;
  margin-right: 2px;
  cursor: pointer;
}
:deep(.jeecg-tree-header) {
  border-bottom: none;
}
//update-end---author:wangshuai ---date:20230202  for：抽屉弹窗标题图标下拉样式------------
</style>
